//
//  BGHomeViewModel.swift
//  WeiboSwift
//
//  Created by 战场原黑仪 on 16/7/25.
//  Copyright © 2016年 战场原黑仪. All rights reserved.
//

import UIKit

class BGHomeViewModel: NSObject {
    //存储每个cell的模型
    lazy var statusList: [BGHomeCellModel] = [BGHomeCellModel]()
}

//MARK: - 微博首页内容
extension BGHomeViewModel {
    
    func loadHomeData(isPullUp: Bool, isFinish:(isSuc: Bool)->()) {
        
        //上拉加载  需要给服务器maxid   sinceid == 0
        //下拉刷新  需要给服务器sinceId   maxId == 0
        var maxId:Int64 = 0
        var sinceId: Int64 = 0
        if isPullUp {
            //上拉加载
            maxId = statusList.last?.statusModel?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        }else {
            // 下拉刷新
            sinceId = statusList.last?.statusModel?.id ?? 0
        }
        
        //获取数据
        BGNetworkTools.shareTools.homeLoadData(sinceId, maxId: maxId, success: { (response) in
            //判断是否能转为数组
            guard let res = response?["statuses"] as? [[String: AnyObject]] else {
                isFinish(isSuc: false)
                return
            }
            
            //定义一个临时可变数组
            var tempArray: [BGHomeCellModel] = [BGHomeCellModel]()
            //遍历数组
            for dict in res {
                //字典转模型
                let model: BGStatusModel = BGStatusModel(dict: dict)
                //创建视图模型
                let statusModel: BGHomeCellModel = BGHomeCellModel(statusModel: model)
                //存入可变数组
                tempArray.append(statusModel)
            }
            //给属性赋值
            if isPullUp {
                //上拉加载
                self.statusList = self.statusList+tempArray
            }else {
                //下拉刷新
                self.statusList = tempArray + self.statusList
            }
            isFinish(isSuc: true)

            }) { (error) in
                print("loadHomeData\(error)")
                isFinish(isSuc: false)
        }
    }
    
}
